package com.common.plugin;

import java.util.List;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.demo.common.model.QuartzJob;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import com.quartz.timertask.QuartzManager;

public class QuartzPlugin implements IPlugin {
	public static final int STATUS_PAUSE = 0;//暂停

	public static final int STATUS_ADD = 1;//添加

	public static final int STATUS_DEL = 2;//删除

	public static final int STATUS_RESUME = 3;//恢复

	public static final QuartzManager manager = new QuartzManager();

	private static final SchedulerFactory gSchedulerFactory = new StdSchedulerFactory(); 
	
	private static final Log log = Log.getLog(QuartzPlugin.class);
	@Override
	public boolean start() {
		try {
			Scheduler scheduler = gSchedulerFactory.getScheduler();
			manager.setScheduler(scheduler);
			manager.start();
			
			startJobs();
			
		} catch (SchedulerException e) {
			e.printStackTrace();
			log.error("定时任务Plugin启动失败!初始化调度器发生错误:" + e.getMessage(), e);
			return false;
		}
		return true;
	}

	@Override
	public boolean stop() {
		try {
			manager.shutdown();
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private void startJobs() {
		List<QuartzJob> jobList = QuartzJob.dao.findListByStatus(STATUS_RESUME);
		jobList.addAll(QuartzJob.dao.findListByStatus(STATUS_ADD));
		for (QuartzJob quartzJob : jobList) {
			try {
				manager.initJob(quartzJob, Class.forName(quartzJob.getJobClassName()));
			} catch (ClassNotFoundException e) {
				log.error("启动定时任务失败!" + quartzJob.getJobClassName() + "不存在:" + e.getMessage(), e);
				e.printStackTrace();
			} catch (SchedulerException e) {
				log.error("启动定时任务失败!" + e.getMessage(), e);
				e.printStackTrace();
			}
		}
	}

}

/**
 * 守护线程，定时扫描数据库，及时更新定时任务的状态
 *//*
class MainJob implements Job {

	private static final Log log = Log.getLog(MainJob.class);

	@Override
	public void execute(JobExecutionContext job) throws JobExecutionException {
		List<QuartzJob> jobList = QuartzJob.dao.findAll();
		if (jobList != null && jobList.size() > 0) {
			for (QuartzJob quartzJob : jobList) {
				switch (quartzJob.getJobStatus()) {
				case QuartzPlugin.STATUS_ADD:
					try {
						QuartzPlugin.manager.initJob(quartzJob, Class.forName(quartzJob.getJobClassName()));
					} catch (ClassNotFoundException e) {
						log.error("定时任务初始化失败!" + e.getMessage(), e);
					}
					break;
				case QuartzPlugin.STATUS_DEL:
					QuartzPlugin.manager.deleteJob(quartzJob);
					break;
				case QuartzPlugin.STATUS_PAUSE:
					QuartzPlugin.manager.pauseJob(quartzJob);
					break;
				case QuartzPlugin.STATUS_RESUME:
					QuartzPlugin.manager.resumeJob(quartzJob);
				}
			}
		}
	}

}*/
